package cgroups

import (
	"github.com/sirupsen/logrus"
	"mydocker/cgroups/fs2"
	"mydocker/cgroups/resource"
)

type CgroupManagerV2 struct {
	Path       string
	Resource   *resource.ResourceConfig
	Subsystems []resource.Subsystem
}

func NewCgroupManagerV2(path string) *CgroupManagerV2 {
	return &CgroupManagerV2{
		Path:       path,
		Subsystems: fs2.Subsystems,
	}
}

// Apply 将进程 pid 加入到这个 cgroup 中
func (c *CgroupManagerV2) Apply(pid int) error {
	for _, subsystem := range c.Subsystems {
		err := subsystem.Apply(c.Path, pid)
		if err != nil {
			logrus.Errorf("apply subsystem:%s error:%v", subsystem.Name(), err)
		}
	}
	return nil
}

// Set 设置 cgroup 资源限制
func (c *CgroupManagerV2) Set(res *resource.ResourceConfig) error {
	for _, subsystem := range c.Subsystems {
		err := subsystem.Set(c.Path, res)
		if err != nil {
			logrus.Errorf("apply subsystem:%s error:%v", subsystem.Name(), err)
		}
	}
	return nil
}

// Destroy 释放 cgroup
func (c *CgroupManagerV2) Destroy() error {
	for _, subsystem := range c.Subsystems {
		if err := subsystem.Remove(c.Path); err != nil {
			logrus.Errorf("remove subsystem:%s error:%v", subsystem.Name(), err)
		}
	}
	return nil
}
